package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojo.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.BCrypt;
import org.springframework.stereotype.Service;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    /**
     * 登录接口
     *   二合一，用户登录也是有游客登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        if (dto==null){
            return ResponseResult.okResult(AppJwtUtil.getToken(0L));
        }
        //1.校验参数
        LambdaQueryWrapper<ApUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApUser::getPhone,dto.getPhone());
        ApUser user = getOne(queryWrapper);
        if(user==null){
            //2.1 如果用户不存在，创建用户
            user = new ApUser();
            user.setName("用户"+dto.getPhone());
            user.setPassword(BCrypt.hashpw(dto.getPassword(), BCrypt.gensalt()));
            user.setPhone(dto.getPhone());
            save(user);
            ApUser newUser = getOne(queryWrapper);
            user = newUser;
            Integer id = user.getId();
            Long idL= id.longValue();
            String token = AppJwtUtil.getToken(idL);

            return ResponseResult.okResult(token);
        }else{
            //2.2 如果用户存在，校验密码
            if(!BCrypt.checkpw(dto.getPassword(),user.getPassword())){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码错误");
            }else {
                Integer id = user.getId();
                Long idL= id.longValue();
                String token = AppJwtUtil.getToken(idL);
                return ResponseResult.okResult(token);
            }
        }
    }

    /**
     * 根据用户id获取用户实体
     *
     * @param userId
     * @return
     */
    @Override
    public ResponseResult<ApUser>findUserById(Integer userId) {
        ApUser apUser = getById(userId);
        return ResponseResult.okResult(apUser);
    }
}
